package net;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author Justin Parker
 * @Date 2024/7/19 0019 17:24
 * @Version 1.0
 */
public class ThreadChatServer {
    private ServerSocket serverSocket;
    //构建一个集合对象，存储所有客户端的输出流对象
    private List<PrintWriter> allOut = new ArrayList<>();
    private static final int PORT;

    static {
        PORT = 8088;
    }

    public ThreadChatServer() {
        try {
            System.out.println("服务器开始启动.....");
            serverSocket = new ServerSocket(PORT);
            System.out.println("服务器启动成功,正在" + PORT + "端口监听中.....");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("服务器启动失败！");
            System.exit(-1);
        }
    }

    private class ClientHandler implements Runnable {
        private Socket socket;
        private String host;

        public ClientHandler(Socket socket) {
            this.socket = socket;
            host = this.socket.getInetAddress().getHostName();
        }

        public void run() {
            PrintWriter pw = null;
            try {
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(
                                socket.getInputStream(), StandardCharsets.UTF_8));

                 pw = new PrintWriter(
                        new BufferedWriter(
                                new OutputStreamWriter(
                                        socket.getOutputStream(),
                                        StandardCharsets.UTF_8)), true);
                //将每个线程的输出流对象加入到集合中
                synchronized (allOut){
                allOut.add(pw);
                }
                //3.通过此对象读取数据
                String line = null;
                while ((line = br.readLine()) != null) {
                    System.out.println(host + "客户端读取的数据：" + line);
                    //写数据给客户端（后续是要在这里，把一个客户端的数据转发给所有客户端）
                    synchronized (allOut){
                    for (PrintWriter out : allOut) {
                        out.println(host + "说：" + line);
                    }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            finally {
                try{
                    synchronized (allOut){
                    allOut.remove(pw);
                    }
                    socket.close();
                    System.out.println("客户端断开连接！");
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
    }

    //启动服务读取数据
    public void start() {
        while (true) {
            try {
                Socket socket = serverSocket.accept();
                System.out.println("客户端连接成功！");

                new Thread(new ClientHandler(socket)).start();

            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }


    public static void main(String[] args) {
        new ThreadChatServer().start();
    }
}

